#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QMetaObject>
#include <QStringListModel>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QMenu>
#include <QFile>
#include <QIODevice>
#include <QCommonStyle>

MainWindow::MainWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MainWindow),bold(),nobold(),
    diskFileName( "disk.data"),
    diskeditor(this),
    settings("mslagmu","GDM")
{


    createMenuTray();

    ui->setupUi(this);
    initDriveList();
    bold.setBold(true);
    readConfig();

    //setWindowFlags( Qt::SplashScreen );

}


void MainWindow::createMenuTray(){
    QCommonStyle style;
    trayMenu = new QMenu(this);
    trayMenu->setObjectName("trayMenu");

    quitAction = trayMenu->addAction(style.standardIcon(QStyle::SP_DialogCloseButton),tr("Quit"));
    saveConfigAction = trayMenu->addAction(style.standardIcon(QStyle::SP_DialogSaveButton),tr("Save the setup"));

    trayMenu->addSeparator();

    tray = new QSystemTrayIcon(QIcon(":/image/gdrive.jpg"),this);
    tray->setObjectName("tray");
    tray->setContextMenu(trayMenu);
    tray->show();
}

void MainWindow::on_tray_activated(QSystemTrayIcon::ActivationReason reason) {

    if ( reason ==  QSystemTrayIcon::Trigger ) {
        if (this->isVisible()) {
            this->hide();
        } else {
            this->show();
        }
    }
}


void MainWindow::createTableLine(const QString & name, const QString & point)
{
    QTreeWidget * table = ui->DisksView;
    QStringList line;
    line << name << point;
    QTreeWidgetItem * item = new QTreeWidgetItem(line);
    table->insertTopLevelItem(table->topLevelItemCount(),item);

    QAction *action = trayMenu->addAction(name);
    actionTrayList.append(action);
    action->setCheckable(true);

}



void MainWindow::on_newDriveBut_clicked()
{
    diskeditor.clear();
    if  ( ! diskeditor.exec() ) return;
    createTableLine(diskeditor.name(),diskeditor.point());
    saveConfigAction->setEnabled(true);

}

void MainWindow::on_modifyDriveBut_clicked()
{
    QTreeWidget * table = ui->DisksView;
    int index = table->currentIndex().row();
    QTreeWidgetItem * item = table->currentItem();

    diskeditor.setName(item->text(0));
    diskeditor.setPoint(item->text(1));

    if  ( ! diskeditor.exec() ) return;

    item->setText(0,diskeditor.name());
    item->setText(1,diskeditor.point());

    actionTrayList.at(index)->setText(diskeditor.name());
    saveConfigAction->setEnabled(true);
}

void MainWindow::on_deleteDriveBut_clicked()
{
    QTreeWidget * table = ui->DisksView;
    int index = table->currentIndex().row();
    qDebug() << table->topLevelItemCount();
    QTreeWidgetItem * item = table->takeTopLevelItem(index);
    delete item;
    trayMenu->removeAction(actionTrayList.takeAt(index));
    qDebug() << table->topLevelItemCount();
    saveConfigAction->setEnabled(true);
}

void MainWindow::enableMountButtons(int index)
{
    if (actionTrayList.at(index)->isChecked()) {
        ui->mountDriveBut->setEnabled(false);
        ui->unMountDriveBut->setEnabled(true);
    } else {
        ui->mountDriveBut->setEnabled(true);
        ui->unMountDriveBut->setEnabled(false);
    }
}

void MainWindow::readConfig()
{
    int size = settings.beginReadArray("disks");
    for (int i = 0; i < size; ++i) {
        settings.setArrayIndex(i);
        QString name = settings.value("name").toString();
        QString point = settings.value("point","<Empty>").toString();
        createTableLine(name,point);
    }
     settings.endArray();
     saveConfigAction->setEnabled(false);
}

void MainWindow::writeConfig()
{
    QTreeWidget * table = ui->DisksView;
    settings.beginWriteArray("disks");
    for (int i = 0; i < table->topLevelItemCount(); ++i) {
        QTreeWidgetItem * item = table->topLevelItem(i);
        settings.setArrayIndex(i);
        settings.setValue("name",item->text(0));
        settings.setValue("point",item->text(1));
    }
    settings.endArray();
    saveConfigAction->setEnabled(false);
}

void MainWindow::on_DisksView_itemSelectionChanged()
{
    QTreeWidget * table = ui->DisksView;
    int index = table->currentIndex().row();
    enableMountButtons(index);
}

void MainWindow::on_tray_messageClicked (){

}


void MainWindow::on_mountDriveBut_clicked(){
    QTreeWidget * table = ui->DisksView;
    int index = table->currentIndex().row();
    mount(index);
}

void MainWindow::on_unMountDriveBut_clicked(){
    QTreeWidget * table = ui->DisksView;
    int index = table->currentIndex().row();
    unmount(index);
}

void  MainWindow::on_trayMenu_triggered ( QAction * action ){

    int index = actionTrayList.indexOf(action);
    if ( action == quitAction ) {

        if (saveConfigAction->isEnabled()) {
            int ret = QMessageBox::warning(this, tr("Warning !!"),
                                        tr("The setup has been modified.\n"
                                           "Do you want to save your changes?"),
                                        QMessageBox::Save | QMessageBox::Discard
                                        | QMessageBox::Cancel,
                                        QMessageBox::Save);
            if ( ret == QMessageBox::Cancel ) return;
            if ( ret == QMessageBox::Save ) writeConfig();
        }

        QCoreApplication::exit(0);
        return;
    }

    if ( action == saveConfigAction ) {
        writeConfig();

        return;
    }

    if ( action->isChecked() ) {
        mount(index);
    } else {
        unmount(index);
    }

}

void MainWindow::lineApparence(int index, bool ismounted)
{
    QTreeWidget * table = ui->DisksView;
    QTreeWidgetItem * item = table->topLevelItem(index);
    if (ismounted) {
        item->setFont(0,bold);
        item->setFont(1,bold);
    } else {
        item->setFont(0,nobold);
        item->setFont(1,nobold);
    }
    actionTrayList.at(index)->setChecked(ismounted);
    int selectedIdex =  table->currentIndex().row();
    if (selectedIdex == index) enableMountButtons(index);
}

void MainWindow::mount(int index)
{
   lineApparence(index, true);
}
void MainWindow::unmount(int index)
{
    lineApparence(index, false);
}


void MainWindow::initDriveList()
{


}


MainWindow::~MainWindow()
{

    delete ui;
}

void MainWindow::close()
{

}
